<template>
  <div class="goods">
    <!-- 1、面包屑导航  -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2.卡片 -->
    <el-card>
      <!-- 2-1、搜索框和下拉按钮  -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="query"
            placeholder="输入商品名称"
            clearable
            @clear="search"
          >
            <template #append>
              <el-button :icon="Search" @click="search" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button :icon="Plus" type="primary" class="add-btn" @click="toAdd"
            >添加商品</el-button
          >
          <el-dropdown split-button type="primary" @command="handleClick">
            导出到文件
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="excel"> Excel </el-dropdown-item>
                <el-dropdown-item command="pdf">PDF</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
      <!-- 2-2、商品的列表 -->
      <el-table
        :data="goodsList"
        border
        stripe
        fit
        :header-cell-style="header_cell_style"
        style="width: 100%"
        ref="goodsTable"
        id="goodsTable"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="商品价格" align="center">
          <template #default="props">
            {{ "￥" + props.row.goods_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="goods_number" label="商品数量" align="center" />
        <el-table-column label="创建日期" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ $formatTime(row.add_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              :icon="EditPen"
              size="default"
              @click="showUpdateGoodsDialog(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              size="default"
              @click="deleteGoods(row.goods_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2-3 分页器 -->
      <el-pagination
        :currentPage="pagenum"
        :page-size="pagesize"
        :page-sizes="[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup>
/*---------------------- 引入资源 ---------------------- */
import { ref, onMounted, getCurrentInstance } from "vue";
import {
  ArrowRight,
  Search,
  Plus,
  EditPen,
  Delete,
} from "@element-plus/icons-vue";
import { error, success, confirm, info } from "@/utils/message";
import { useRouter } from "vue-router";
import request from "@/utils/request";
import html2canvas from "html2canvas";
import JsPDF from "jspdf";
/*---------------------- 定义变量 ---------------------- */

let goodsTable = ref(),
  header_cell_style = {
    backgroundColor: "#00A0ff",
    color: "#fff",
    textAlign: "center",
  }, // 表格头部的单元格样式
  goodsList = ref([]),
  total = ref(0), // 角色的总数
  pagenum = ref(1), // 当前页码
  pagesize = ref(10), // 一页几条
  query = ref(""),
  { $formatTime } = getCurrentInstance().appContext.config.globalProperties,
  router = useRouter();

/*---------------------- 功能函数 ---------------------- */
function deleteGoods(id) {
  confirm("要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let option = {
        url: `goods/${id}`,
        type: "delete",
      };
      try {
        let { data: res } = await request(option);
        if (res.meta.status !== 200) {
          return error(res.meta.msg);
        }
        success(res.meta.msg);
        getGoodsList();
      } catch (error) {
        console.log(error);
      }
    }).catch(() => {
      info("您取消了删除");
    });
    
}
//到商品添加页面
function toAdd() {
  router.push("/goodsAdd");
}
//商品的查询
async function search() {
  pagenum.value = 1;
  getGoodsList();
}
// 一页几条发生变化执行的操作
function handleSizeChange(size) {
  pagesize.value = size;
  pagenum.value = 1;
  getGoodsList();
}
// 页码发生变化时执行的操作
function handleCurrentChange(num) {
  pagenum.value = num;
  getGoodsList();
}
function exprotsToExcel() {
  // 1、获得要导出的数据
  let arr = goodsList.value;
  if (!arr || arr.length === 0) {
    return;
  }
  for (let item of arr) {
    item.add_time = $formatTime(item.add_time);
    item.upd_time = $formatTime(item.upd_time);
  }
  // 2、拼接表头行
  let str = "index,",
    item0 = arr[0],
    keys = Reflect.ownKeys(item0);
  for (let key of keys) {
    str += key + ",";
  }
  str += "\n";
  // 3、拼接所有商品对象的值
  for (let i = 0; i < arr.length; i++) {
    let values = Object.values(arr[i]);
    str += i + 1 + "\t,";
    str += values.join("\t,");
    str += "\n";
  }
  // 4、模拟a标签的点击下载功能
  let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str),
    link = document.createElement("a");
  link.href = uri;
  link.download = "商品列表.csv";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
function exprotsToPdf() {
  let ele = document.getElementById("goodsTable");
  ele.style.background = "#fff";
  // 获得该容器的宽
  let eleW = ele.offsetWidth,
    // 获得该容器的高
    eleH = ele.offsetHeight,
    // 获得该容器到文档顶部的距离
    eleOffsetTop = ele.offsetTop,
    // 获得该容器到文档最左的距离
    eleOffsetLeft = ele.offsetLeft,
    canvas = document.createElement("canvas"),
    abs = 0,
    win_in = document.documentElement.clientWidth || document.body.clientWidth,
    win_out = window.innerWidth;
  if (win_out > win_in) {
    // abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
    abs = (win_out - win_in) / 2; // 获得滚动条宽度的一半
  }
  canvas.width = eleW * 2; // 将画布宽&&高放大两倍
  canvas.height = eleH * 2;
  let context = canvas.getContext("2d");
  context.scale(2, 2);
  context.translate(-eleOffsetLeft - abs, -eleOffsetTop);
  // 这里默认横向没有滚动条的情况，因为offset.left(),有无滚动条的时候存在差值，因此
  // translate的时候，要把这个差值去掉
  // html2canvas(element).then( (canvas)=>{ //报错
  // html2canvas(element[0]).then( (canvas)=>{
  html2canvas(ele, {
    dpi: 900,
    // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
    useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
  }).then((canvas) => {
    let contentWidth = canvas.width,
      contentHeight = canvas.height,
      //一页pdf显示html页面生成的canvas高度;
      pageHeight = (contentWidth / 592.28) * 841.89,
      //未生成pdf的html页面高度
      leftHeight = contentHeight,
      //页面偏移
      position = 0,
      //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      imgWidth = 595.28,
      imgHeight = (595.28 / contentWidth) * contentHeight,
      pageData = canvas.toDataURL("image/jpeg", 1.0),
      pdf = new JsPDF("", "pt", "a4");
    //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
    //当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < pageHeight) {
      //在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
      pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
    } else {
      // 分页
      while (leftHeight > 0) {
        pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        //避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    //可动态生成
    pdf.save("goods.pdf");
  });
}
// 2、处理下拉按钮的点击事件
function handleClick(args) {
  if (args === "excel") {
    return exprotsToExcel();
  }
  exprotsToPdf();
}
// 请求商品列表数据
async function getGoodsList() {
  //准备参数
  let option = {
    url: "goods",
    type: "get",
    data: {
      pagenum: pagenum.value,
      pagesize: pagesize.value,
      query: query.value,
    },
  };
  try {
    //发送请求
    let { data: res } = await request(option);
    //判断结果
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    //解析,保存数据
    goodsList.value = res.data.goods;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
}
/*---------------------- 生命周期函数 ---------------------- */
onMounted(() => {
  getGoodsList();
});
</script>

<style lang="scss" scoped>
.el-card {
  margin: 10px 0;
}
.el-table {
  margin: 20px 0;
}
.el-pagination {
  float: right;
  margin-bottom: 15px;
}
.add-btn {
  margin-right: 20px;
}
</style>